package com.edu.chat.web.controller;

import com.edu.chat.web.common.model.R;
import com.edu.chat.web.covert.FileCovert;
import com.edu.chat.web.service.CsFileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @program: KQAIA
 * @description: 文件上传控制类
 * @author: 无恙
 * @create: 2025-03-06 22:58
 **/

@RestController
@RequestMapping("/chat/oss")
@Slf4j
public class OssController {


	@Autowired
	private CsFileService fileService;


	@RequestMapping(value = "/upload", method = {RequestMethod.POST})
	public R<?> upload(@RequestParam("file") MultipartFile file,@RequestParam("categoryId") String categoryId,@RequestParam("libraryId") String libraryId) throws IOException {
		log.info("文件上传开始,参数：{}",libraryId);
		// 检查文件是否为空
		if (file.isEmpty()) {
			return R.fail("文件不能为空");
		}

		// 验证文件类型和大小
		String contentType = file.getContentType();
		long fileSize = file.getSize();
		if ( fileSize > getMaxFileSize()) {
			return R.fail("文件类型或大小不合法");
		}

		return fileService.upload(FileCovert.covert(file,categoryId,libraryId));
	}


	private long getMaxFileSize() {
		// 返回允许的最大文件大小（例如 5MB）
		return 5 * 1024 * 1024;
	}

	//删除文件
	@GetMapping(value = "/delete")
	public R<?> delete(@RequestParam("id") String id) {
		log.info("文件删除开始,参数：{}",id);
		return fileService.deleteFile(id);
	}

}
